import {useState, useEffect} from 'react'

import _ from 'lodash'

let g_state = {
    girls: [
        {
            name: "kate",
            age: 18,
            like:['sing', 'swing', {
                times: 'dayli'
            }],
        }
    ],
    car: {
        brand: "bmw",
        price: "200w",
        color: 'red',
    },
    menuCollapsed: false,
    cats:[{name:"树"}]
}
let subscriber = {}

export function useModel(path){
    let the_data = _.get(g_state, path)
    let [the_state, setState] = useState(the_data)
    if(_.has(subscriber, path)){
        subscriber[path].push(setState)
    }else{
        subscriber[path]= [setState]
    }
    let _setState = (data)=>{
        if(_.isObject(data) && !_.isArray(data)){
            _.set(g_state, path, {...the_state, ...data})
        }else{
            _.set(g_state, path, data)
        }
        subscriber[path].forEach((setFn) => {
            if(_.isObject(data) && !_.isArray(data)){
                setFn({...the_state, ...data})
            }else{
                setFn(data)
            }
        })
    }
    return [the_state, _setState]
}